package team.bluepen.supermarket.web.servlet;

import team.bluepen.supermarket.constant.Constant;
import team.bluepen.supermarket.constant.Error;
import team.bluepen.supermarket.data.entity.Good;
import team.bluepen.supermarket.util.ServletUtil;
import team.bluepen.supermarket.util.StringUtil;
import team.bluepen.supermarket.web.base.DataServlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 商品添加
 * @author Kai
 */
@WebServlet(name = "GoodAddServlet", urlPatterns = "/api/good-add")
public class GoodAddServlet extends DataServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doPost(req, resp);
        if (!checkUserRole(req)) {
            resp.sendRedirect(requestSource);
            return;
        }

        String requestSource = ServletUtil.getRefererUrl(req);
        String name = req.getParameter(Constant.GOOD_NAME_PARAM);
        if (req.getParameter(Constant.GOOD_ID_PARAM) == null || name == null) {
            resp.sendRedirect(requestSource + "?error=" + Error.ERROR_NULL.getValue());
            return;
        }

        long id = Long.parseLong(req.getParameter(Constant.GOOD_ID_PARAM));
        int amount = 0, price = 0;
        if (!StringUtil.isEmpty(req.getParameter(Constant.GOOD_AMOUNT_PARAM))) {
            amount = Integer.parseInt(req.getParameter(Constant.GOOD_AMOUNT_PARAM));
        }

        if (!StringUtil.isEmpty(req.getParameter(Constant.GOOD_PRICE_PARAM))) {
            price = Integer.parseInt(req.getParameter(Constant.GOOD_PRICE_PARAM));
        }


        String state = req.getParameter(Constant.GOOD_STATE_PARAM);

        Good good = new Good()
                .setId(id)
                .setAmount(Math.max(amount, 0))
                .setPrice(Math.max(price, 0))
                .setState(state)
                .setName(name);
        Error error = goodRepository.createGood(good);
        resp.sendRedirect(requestSource + "?error=" + error.getValue());
    }
}
